package aes.client;

import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.util.Date;
import java.util.Observable;
import java.util.Observer;
import java.util.Vector;

import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.table.*;

import common.*;

public class ExamCheckingUI extends JPanel implements ActionListener, ListSelectionListener, Observer {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7616185346843081489L;
	
	private ClientUI ui;
	private Client c;

	private JTable list;
	private JButton btnBack;
	private JButton btnView;
    private String execCode;

    /**
     * Exam execution code getter
     * @return Exam execution code
     */
	public String getExamExecutionCode() {
		return execCode;
	}

	/**
	 * Exam execution code setter
	 * @param code Exam execution code
	 */
	public void setExamExecutionCode(String code) {
		execCode = code;
	}

	/**
	 * Constructor
	 * @param c Client object reference
	 * @param ui ClientUI object reference
	 */
	public ExamCheckingUI(Client c,ClientUI ui) {
		super();
		this.ui = ui;
		this.c = c;
	
		JFrame frame = new JFrame();
		frame.setSize(640, 480);
		frame.getContentPane().add(this);
		
		// Handle messages from server.
		c.addObserver(this);
		setLayout(new GridBagLayout());

		JPanel panel = new JPanel();
		panel.setBorder(new LineBorder(new Color(0, 0, 0), 2, true));
		panel.setPreferredSize(new Dimension(600,400));

		GridBagConstraints gbc_panel = new GridBagConstraints();
		gbc_panel.insets = new Insets(5, 0, 5, 0);
		gbc_panel.gridx = 0;
		gbc_panel.gridy = 0;
		add(panel,gbc_panel);
		GridBagLayout gbl_panel = new GridBagLayout();
		gbl_panel.rowWeights = new double[]{0.0, 1.0};
		gbl_panel.columnWeights = new double[]{0.0, 1.0};
		panel.setLayout(gbl_panel);

		JLabel lblAesTitle = new JLabel("Grade Approving:");
		lblAesTitle.setHorizontalAlignment(SwingConstants.CENTER);
		lblAesTitle.setBounds(7, 10, 70, 17);
		lblAesTitle.setFont(new Font("Tahoma", Font.BOLD, 14));

		GridBagConstraints gbc_lblAesTitle = new GridBagConstraints();
		gbc_lblAesTitle.gridwidth = 4;
		gbc_lblAesTitle.fill = GridBagConstraints.BOTH;
		gbc_lblAesTitle.insets = new Insets(5, 0, 5, 5);
		gbc_lblAesTitle.gridx = 0;
		gbc_lblAesTitle.gridy = 0;
		panel.add(lblAesTitle, gbc_lblAesTitle);
///
		
		list = new JTable(){
			/**
			 * 
			 */
			private static final long serialVersionUID = 2684500652668234277L;

			public boolean isCellEditable(int rowIndex, int colIndex) {
				return false; //Disallow the editing of any cell
			}};
			list.setModel(new DefaultTableModel(
					new Object[][] {
					},
					new String[] {
							"AutoExamId", "Student ID", "Solving Time", "Grade" , "Cheating warning"
					}
					) {
				/**
				 * 
				 */
				private static final long serialVersionUID = -4567261985989300298L;
				@SuppressWarnings("rawtypes")
				Class[] columnTypes = new Class[] {
					String.class, String.class, String.class, String.class, String.class
				};
				@SuppressWarnings({ "unchecked", "rawtypes" })
				public Class getColumnClass(int columnIndex) {
					return columnTypes[columnIndex];
				}
			});
			list.removeColumn(list.getColumnModel().getColumn(0));
			list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
			list.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
			list.getColumnModel().getColumn(0).setPreferredWidth(80);
			list.getColumnModel().getColumn(1).setPreferredWidth(80);
			list.getColumnModel().getColumn(2).setPreferredWidth(80);
			list.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
			JScrollPane scrollPane = new JScrollPane(list);
			list.setFillsViewportHeight(true);
			list.getSelectionModel().addListSelectionListener(this);
			GridBagConstraints gbc_list = new GridBagConstraints();
			gbc_list.insets = new Insets(5, 5, 5, 5);
			gbc_list.fill = GridBagConstraints.BOTH;
			gbc_list.gridwidth = 4;
			gbc_list.gridx = 0;
			gbc_list.gridy = 1;
			panel.add(scrollPane, gbc_list);
			
			btnBack = new JButton("Back", new ImageIcon(QuestionsManagerUI.class.getResource("/aes/client/images/back.png")));
			btnBack.addActionListener(this); 
			GridBagConstraints gbc_btnBack = new GridBagConstraints();
			gbc_btnBack.insets = new Insets(5, 5, 5, 5);
			gbc_btnBack.gridx = 0;
			gbc_btnBack.gridy = 3;
			panel.add(btnBack, gbc_btnBack);
			btnBack.setBounds(353, 7, 57, 23);
			
			btnView = new JButton("View", new ImageIcon(ExamCheckingUI.class.getResource("/aes/client/images/Exam.png")));
			btnView.addActionListener(this); 
			GridBagConstraints gbc_btnView = new GridBagConstraints();
			gbc_btnView.insets = new Insets(5, 5, 5, 5);
			gbc_btnView.gridx = 3;
			gbc_btnView.gridy = 3;
			panel.add(btnView, gbc_btnView);
			btnView.setBounds(353, 7, 57, 23);
	}

	/**
	 * Server message received event handler
	 */
	@Override
	public void update(Observable arg0, Object arg1) {
		if (arg1 instanceof CommandMessage) {
			CommandMessage ms=(CommandMessage)arg1;
			if (ms.getCommand().equals(CommandMessage.ACKNOWLEDGE_MESSAGE) && ((String)ms.getParams()[0]).equals(CommandMessage.GET_EXECUTED_STUDENT_EXAMS)) {
				// Disable view button.
				btnView.setEnabled(false);
				StudentExam[] exams = (StudentExam[]) ms.getParams()[1];
				if (exams != null) {
					// Bind.
					DefaultTableModel model =(DefaultTableModel) list.getModel();
					model.setRowCount(0);
					for (StudentExam se : exams) {
						// Show only not approved 
						if (!se.isApproved()) {
							String[] row = new String[5];
							if (se.getExam() instanceof AutoExamExecution) {
								row[0] = Integer.toString(((AutoExamExecution)se.getExam()).getExam());
							}
							row[1] = Integer.toString(se.getStudentId());
							Date started = se.getTimeStarted();
							Date finished = se.getTimeFinished();
							if (started != null && finished != null) {
								long diff = (finished.getTime() - started.getTime()) / 1000;
								long diffSeconds = diff % 60;
								long diffMinutes = diff / 60 % 60;
								long diffHours = diff / 3600;
								row[2] = String.format("%02d", diffHours) + ":" + String.format("%02d", diffMinutes) + ":" + String.format("%02d", diffSeconds);
							}
							row[3] = Integer.toString(se.getGrade());
							if (se.isCheater()) {
								row[4] = "V";
							}
							model.addRow(row);
						}
					}
					list.setModel(model);
				}
			}
		}
	}

	/**
	 * List value changed event handler
	 */
	@Override
	public void valueChanged(ListSelectionEvent arg0) {
		btnView.setEnabled(true);
	}

	/**
	 * Action performed event handler
	 */
	@SuppressWarnings("static-access")
	@Override
	public void actionPerformed(ActionEvent arg0) {
		if (arg0.getSource().equals(btnBack)) {
			ui.SetContent(ui.EXAM_EXECUTION_MANAGER_SCREEN);
		}
		else if (arg0.getSource().equals(btnView)) {
			// View exam button was clicked.
			DefaultTableModel model =(DefaultTableModel) list.getModel();
			Vector<?> o1 = (Vector<?>) model.getDataVector().get(list.getSelectedRow());
			int studentId = Integer.parseInt((String)o1.get(1));
			if (o1.get(0) == null) {
				// Manual.
				ui.SetContent(ui.MANUAL_EXAM_GRADE_APPROVAL_SCREEN);
				CheckManualExamUI cme= ((CheckManualExamUI)ui.getContentPane());
				cme.setStudentID(studentId);
				cme.setCode(execCode);

			}
			else {
				// Automatic.
				ui.SetContent(ui.EXAM_EXECUTION_FORM_SCREEN);
				Container cont = ui.getContentPane();
				if (cont instanceof ExamExecutionFormUI) {
					ExamExecutionFormUI form = (ExamExecutionFormUI)cont;
					form.loadExam(execCode, studentId);
				}
			}
		}
	}
	
	/**
	 * Load student exams
	 */
	public void loadExams() {
		CommandMessage msg = new CommandMessage(CommandMessage.GET_EXECUTED_STUDENT_EXAMS, new Object[] {execCode, ui.getUser().getId()});
		try {
			c.sendToServer(msg);
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

}
